//
//  CYMainController.m
//  cyjf
//
//  Created by tauCross on 2017/5/3.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYMainController.h"

#import "CYHomeViewController.h"
#import "CYFinanceViewController.h"
#import "CYMineViewController.h"
#import "CYDiscoverViewController.h"

#import "CYLogInViewController.h"
#import "CYCouponsViewController.h"

#import "CYGlobal.h"



@interface CYMainController ()<UITabBarControllerDelegate>

@property(nonatomic, strong)CYViewController *logInViewController;

@property(nonatomic, strong)CYNavigationController *nav;
@property(nonatomic, strong)UIImageView *couponHintView;

@end


@implementation CYMainController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+ (instancetype)standardController
{
    static CYMainController *controller = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        controller = [[CYMainController alloc] init];
        controller.nav = [[CYNavigationController alloc] initWithRootViewController:controller];
    });
    return controller;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self checkCouponHint];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tabBar.translucent = NO;
    [self.tabBar setBackgroundImage:[[UIImage alloc] init]];
    [self.tabBar setShadowImage:[UIImage imageWithColor:HEXCOLOR(@"ECECEC") size:CGSizeMake(1, 1)]];
    [self createComponents];
    [self resetTabItems];
    [self setupComponents];
    self.delegate = self;
    
    self.couponHintView = [[UIImageView alloc] initWithImage:CYImage(@"ico_nav_coupon_deadline")];
    self.couponHintView.bottom = 10;
    self.couponHintView.hidden = YES;
    [self.tabBar addSubview:self.couponHintView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkCouponHint) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)createComponents
{
    self.homeNavigationController = [[CYNavigationController alloc] initWithRootViewController:[[CYHomeViewController alloc] init]];
    self.financeNavigationController = [[CYNavigationController alloc] initWithRootViewController:[[CYFinanceViewController alloc] init]];
    self.mineNavigationController = [[CYNavigationController alloc] initWithRootViewController:[[CYMineViewController alloc] init]];
    self.discoverNavigationController = [[CYNavigationController alloc] initWithRootViewController:[[CYDiscoverViewController alloc] init]];
    self.logInViewController = [[CYViewController alloc] init];
}

- (void)resetTabItems
{
    {
        self.homeNavigationController.tabBarItem.title = @"首页";
        [self.homeNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : HEXCOLOR(@"999999")} forState:UIControlStateNormal];
        [self.homeNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : APP_DEFAULT_COLOR_RED} forState:UIControlStateSelected];
        self.homeNavigationController.tabBarItem.image = [CYImage(@"tab_home") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.homeNavigationController.tabBarItem.selectedImage = [CYImage(@"tab_home_selected") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    {
        self.financeNavigationController.tabBarItem.title = @"理财";
        [self.financeNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : HEXCOLOR(@"999999")} forState:UIControlStateNormal];
        [self.financeNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : APP_DEFAULT_COLOR_RED} forState:UIControlStateSelected];
        self.financeNavigationController.tabBarItem.image = [CYImage(@"tab_finance") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.financeNavigationController.tabBarItem.selectedImage = [CYImage(@"tab_finance_selected") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    {
        self.mineNavigationController.tabBarItem.title = @"我的";
        [self.mineNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : HEXCOLOR(@"999999")} forState:UIControlStateNormal];
        [self.mineNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : APP_DEFAULT_COLOR_RED} forState:UIControlStateSelected];
        self.mineNavigationController.tabBarItem.image = [CYImage(@"tab_mine") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.mineNavigationController.tabBarItem.selectedImage = [CYImage(@"tab_mine_selected") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    {
        self.discoverNavigationController.tabBarItem.title = @"发现";
        [self.discoverNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : HEXCOLOR(@"999999")} forState:UIControlStateNormal];
        [self.discoverNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : APP_DEFAULT_COLOR_RED} forState:UIControlStateSelected];
        self.discoverNavigationController.tabBarItem.image = [CYImage(@"tab_find") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.discoverNavigationController.tabBarItem.selectedImage = [CYImage(@"tab_find_selected") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    {
        self.logInViewController.tabBarItem.title = @"登录";
        [self.homeNavigationController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : HEXCOLOR(@"999999")} forState:UIControlStateNormal];
        self.logInViewController.tabBarItem.image = [CYImage(@"tab_mine") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
}

- (void)setupComponents
{
    @weakify(self);
    [TCRACObserve(CYStandardAuthManager, currentAuth) subscribeNext:^(id x) {
        @strongify(self);
        if(CYStandardAuthManager.currentAuth)
        {
            self.viewControllers = @[self.homeNavigationController, self.financeNavigationController, self.discoverNavigationController, self.mineNavigationController];
        }
        else
        {
            self.viewControllers = @[self.homeNavigationController, self.financeNavigationController, self.discoverNavigationController, self.logInViewController];
        }
    }];
}

- (void)showLogIn
{
    if(CYSharedGlobal.loginShowing == NO)
    {
        CYSharedGlobal.loginShowing = YES;
        CYNavigationController *logInNavigationController = [[CYNavigationController alloc] initWithRootViewController:[[CYLogInViewController alloc] init]];
        [self presentViewController:logInNavigationController animated:YES completion:nil];
    }
}

- (void)goHome
{
    [self.homeNavigationController popToRootViewControllerAnimated:NO];
    [self.financeNavigationController popToRootViewControllerAnimated:NO];
    [self.mineNavigationController popToRootViewControllerAnimated:NO];
    [self.discoverNavigationController popToRootViewControllerAnimated:NO];
    [self setSelectedViewController:self.homeNavigationController];
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)goFinance
{
    [self.homeNavigationController popToRootViewControllerAnimated:NO];
    [self.financeNavigationController popToRootViewControllerAnimated:NO];
    [self.mineNavigationController popToRootViewControllerAnimated:NO];
    [self.discoverNavigationController popToRootViewControllerAnimated:NO];
    [self setSelectedViewController:self.financeNavigationController];
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)goMine
{
    [self.homeNavigationController popToRootViewControllerAnimated:NO];
    [self.financeNavigationController popToRootViewControllerAnimated:NO];
    [self.mineNavigationController popToRootViewControllerAnimated:NO];
    [self.discoverNavigationController popToRootViewControllerAnimated:NO];
    [self setSelectedViewController:self.mineNavigationController];
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)goCoupon
{
    [self.homeNavigationController popToRootViewControllerAnimated:NO];
    [self.financeNavigationController popToRootViewControllerAnimated:NO];
    [self.mineNavigationController popToRootViewControllerAnimated:NO];
    [self.discoverNavigationController popToRootViewControllerAnimated:NO];
    [self.mineNavigationController pushViewController:[[CYCouponsViewController alloc] init] animated:NO];
    [self setSelectedViewController:self.mineNavigationController];
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)goDiscover
{
    [self.homeNavigationController popToRootViewControllerAnimated:NO];
    [self.financeNavigationController popToRootViewControllerAnimated:NO];
    [self.mineNavigationController popToRootViewControllerAnimated:NO];
    [self.discoverNavigationController popToRootViewControllerAnimated:NO];
    [self setSelectedViewController:self.discoverNavigationController];
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

#pragma mark - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if(viewController == self.homeNavigationController && tabBarController.selectedViewController != self.homeNavigationController)
    {
        [MobClick event:UM_EVENT_0017];
    }
    if(viewController == self.financeNavigationController && tabBarController.selectedViewController != self.financeNavigationController)
    {
        [MobClick event:UM_EVENT_0018];
    }
    if(viewController == self.mineNavigationController && tabBarController.selectedViewController != self.mineNavigationController)
    {
        [MobClick event:UM_EVENT_0019];
        self.couponHintView.hidden = YES;
        [self tagCouponHint];
    }
    if(viewController == self.logInViewController)
    {
        [MobClick event:UM_EVENT_0020];
        [self showLogIn];
        return NO;
    }
    return YES;
}

#pragma mark - Private Method
- (void)checkCouponHint
{
    if(CYStandardAuthManager.currentAuth.token.length)
    {
        @weakify(self);
        [CYStandardDataAPI user_userAccountWithComplete:^(CYResponse *response) {
            @strongify(self);
            if(response.code == 0)
            {
                NSNumber *coupon = SAFE_NUMBER(response.content[@"soonToExpireCoupon"]);
                if(coupon.integerValue > 0 && [self couponHint] && [self.tabBar.items containsObject:self.mineNavigationController.tabBarItem])
                {
                    self.couponHintView.centerX = (self.tabBar.width / self.tabBar.items.count) * ([self.tabBar.items indexOfObject:self.mineNavigationController.tabBarItem] + 0.5);
                    self.couponHintView.hidden = NO;
                    return;
                }
            }
            self.couponHintView.hidden = YES;
        }];
    }
    else
    {
        self.couponHintView.hidden = YES;
    }
}

- (BOOL)couponHint
{
    NSDictionary *mine_coupon_hint = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"main_coupon_hint"];
    if(![mine_coupon_hint isKindOfClass:[NSDictionary class]])
    {
        mine_coupon_hint = [NSDictionary dictionary];
    }
    if(CYStandardAuthManager.currentAuth.uid && mine_coupon_hint[CYStandardAuthManager.currentAuth.uid.stringValue] && [mine_coupon_hint[CYStandardAuthManager.currentAuth.uid.stringValue] isEqualToString:[[NSDate date] cy_stringWithFormat:@"yyyy-MM-dd"]])
    {
        return NO;
    }
    return YES;
}

- (void)tagCouponHint
{
    NSDictionary *mine_coupon_hint = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"main_coupon_hint"];
    if(![mine_coupon_hint isKindOfClass:[NSDictionary class]])
    {
        mine_coupon_hint = [NSDictionary dictionary];
    }
    NSMutableDictionary *m = [NSMutableDictionary dictionaryWithDictionary:mine_coupon_hint];
    if(CYStandardAuthManager.currentAuth.uid)
    {
        m[CYStandardAuthManager.currentAuth.uid.stringValue] = [[NSDate date] cy_stringWithFormat:@"yyyy-MM-dd"];
        [[NSUserDefaults standardUserDefaults] setObject:m forKey:@"main_coupon_hint"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

@end
